import { login, checkToken } from '../requests'
export const LOGIN = 'LOGIN'
export const LOGIN_START = 'LOGIN_START'
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'
export const LOGOUT = 'LOGOUT'
export const LOGIN_FAILED = 'LOGIN_FAILED'

export const userLogin = () => {
  return {
    type: LOGIN
  }
}

const loginStart = () => {
  return { type: LOGIN_START }
}
const loginSuccess = data => {
  return {
    type: LOGIN_SUCCESS,
    payload: {
      data
    }
  }
}
const loginFailed = () => {
  return { type: LOGIN_FAILED }
}
export const loginStatus = params => {
  return dispatch => {
    dispatch(loginStart())
    login(params).then(res => {
      if (res.data.code === 200) {
        dispatch(loginSuccess(res.data.data))
      } else {
        dispatch(loginFailed())
      }
    })
  }
}

export const checkTokenAction = () => {
  //   const { authorationToken } =
  const userLoginInfo = JSON.parse(window.localStorage.getItem('userLoginInfo'))
  return dispatch => {
    if (!userLoginInfo) {
      return
    } else {
      dispatch(loginStart())
      checkToken(userLoginInfo.authorationToken).then(res => {
        if (res.status === 200) {
          console.log(res.data.data)
          dispatch(
            loginSuccess({
              ...userLoginInfo,
              authorationToken: res.data.data.token
            })
          )
        } else {
          dispatch(loginFailed())
        }
      })
    }
  }
}

export const logout = () => {
  return {
    type: LOGOUT
  }
}
